package linker.buddy;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import linker.account.Account;

import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;

public class BuddyInfo extends JFrame implements ActionListener {
	// @_@
	private static final long serialVersionUID = 1L;

	private JButton deleteButton = new JButton("Delete");

	private JButton saveButton = new JButton("Save");

	private RosterEntry entry;

	private JTextField field = new JTextField(15);

	public BuddyInfo(RosterEntry entry) {
		super(entry.getUser() + " 's info");

		this.entry = entry;

		Container container = getContentPane();

		JPanel tempPanel = new JPanel();

		tempPanel.add(new JLabel("NickName"));
		field.setText(entry.getName() == null ? entry.getUser() : entry
				.getName());
		tempPanel.add(field);
		deleteButton.addActionListener(this);
		tempPanel.add(deleteButton);
		saveButton.addActionListener(this);
		tempPanel.add(saveButton);
		container.add(tempPanel);

		setSize(400, 200);
		setLocationRelativeTo(null);
		setVisible(true);
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == deleteButton) {

			int option = JOptionPane.showConfirmDialog(this, "Delete "
					+ entry.getUser() + "?", "Delete " + entry.getUser() + "?",
					JOptionPane.OK_CANCEL_OPTION);
			if (option == JOptionPane.CANCEL_OPTION)
				return;

			Presence presence = new Presence(Presence.Type.unsubscribe);
			presence.setFrom(Account.getConnection().getUser());
			presence.setTo(entry.getUser());
			Account.getConnection().sendPacket(presence);

			try {
				Account.getRoster().removeEntry(entry);
			} catch (XMPPException xe) {
				xe.printStackTrace();
			}
			Account.getBuddyList().removeBuddy(entry.getUser());

			this.dispose();
		} else if (e.getSource() == saveButton) {
			entry.setName(field.getText());
		}
	}

	public static void main(String args[]) {
		new BuddyInfo(null);
	}
}
